<?php

 /* hjl:后台-课程的视频管理模块 */

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/cls_image.php');
require "./autoload.php";
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
$img = new cls_image();
/*初始化数据交换对象 */
$exc   = new exchange($ecs->table("course_vedio"), $db, 'vedio_id', 'title');

/*------------------------------------------------------ */
//-- 视频列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list'){

    $smarty->assign('ur_here',      $_LANG['03_article_list']);
    $smarty->assign('action_link',  array('text' => $_LANG['article_add'], 'href' => 'course_vedio.php?act=add'));
    $smarty->assign('full_page',    1);
    $smarty->assign('filter',       $filter);
    $course_list = course_list();  //已经排好序了
    foreach($course_list as $k=>$v){
         $course_list[$k]['title']=str_repeat('&nbsp;', $v['level']*4).$v['title'];
    }
    
    $smarty->assign('course_list',$course_list);
    $vedio_list = get_vedio_list();
    $smarty->assign('filter',          $vedio_list['filter']);
    $smarty->assign('record_count',    $vedio_list['record_count']);
    $smarty->assign('page_count',      $vedio_list['page_count']);

    $sort_flag  = sort_flag($article_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    //print_R($vedio_list);exit;
    $smarty->assign('vedio_list',$vedio_list['arr']);
    $smarty->display('course_vedio_list.htm');

}

/*------------------------------------------------------ */
//-- 翻页，排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    check_authz_json('article_manage');

   $course_list = course_list();
    foreach($course_list as $k=>$v){
         $course_list[$k]['title']=str_repeat('&nbsp;', $v['level']*4).$v['title'];
    }

    $smarty->assign('course_list',$course_list);
    $vedio_list = get_vedio_list();

    $smarty->assign('vedio_list',$vedio_list['arr']);

    $smarty->assign('filter',         $vedio_list['filter']);
    $smarty->assign('record_count',    $vedio_list['record_count']);
    $smarty->assign('page_count',     $vedio_list['page_count']);

    $sort_flag  = sort_flag($vedio_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('course_vedio_list.htm'), '',
        array('filter' => $vedio_list['filter'], 'page_count' => $vedio_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加视频
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'add'){
     /* 权限判断 */
    admin_priv('article_manage');

    /* 取得课程 */
   
    $smarty->assign('course_list', course_list());
    $smarty->assign('ur_here',     '添加视频');
    $smarty->assign('action_link', array('text' =>'视频列表', 'href' => 'course_vedio.php?act=list'));
    $smarty->assign('form_action', 'insert');
    $smarty->assign('img_form_action', 'insert_img');
    /* 七牛上传代码 start */
    //ak、sk信息
    $accessKey = 'H9N6ZegIQ-cm2nIBHF9Gx4aBUK2dMUCj2zlgH4J6';
    $secretKey = 'uHzZsPd4Xds_hw1xaMixtOjOk2Ok_5iMtIZ7xJoA';
    $bucket = 'xinnuo1';

    $auth = new Auth($accessKey, $secretKey);

    $policy=array(

        'callbackUrl'=>'http://hu14.tophp.cn/qiniu_demo1/callback.php',

        'callbackBody' => 'key=$(key)&hash=$(etag)&description=$(x:description)&course_id=$(x:course_id)&is_show=$(x:is_show)'

      );
     //生成上传token
     $upToken = $auth->uploadToken($bucket,null,3600,$policy);

     $smarty->assign('uptoken',$upToken);
   /* 七牛上传代码 end */

    $smarty->display('course_vedio_info.htm');


}

/*------------------------------------------------------ */
//-- 添加视频
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'insert_vedio'){

	/* 权限判断 */
    admin_priv('article_manage');

    $title=trim($_POST['title']);
    $description=$_POST['description'];
    $vedio_url = $_POST['vedio_url'];
    $add_time=gmtime();
    $course_id = $_POST['course_id'];
    $is_show = $_POST['is_show'];
     //print_r($_POST);exit;
   $sql="insert into {$GLOBALS['ecs']->table('course_vedio')}(title,description,vedio_url,add_time,course_id,is_show,qn_key)value('$title','$description','$vedio_url','$add_time','$course_id','$is_show','$title')";
  
   $arr=array('status'=>'','isnert_id'=>'');
   if($GLOBALS['db']->query($sql)){
      $insert_id = $GLOBALS['db']->insert_id();
      $arr['status'] = 1;
      $arr['insert_id'] = $insert_id;
      echo json_encode($arr); exit;
     
   }else{
     $arr['status'] = 0;
     $arr['insert_id'] = $insert_id;
    echo json_encode($arr); exit;
     
   }

}

/*------------------------------------------------------ */
//-- 添加视频封面图片
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'insert_img'){

  /* 权限判断 */
    admin_priv('article_manage');
    $vedio_id=$_POST['vedio_id'];
    $thumb_img =$img->upload_image($_FILES['thumb_img']);
    //echo $thumb_img;exit;
    $sql="update {$GLOBALS['ecs']->table('course_vedio')} set thumb_img='$thumb_img' where vedio_id='$vedio_id'";
    $GLOBALS['db']->query($sql);

    $link[0]['text'] = $_LANG['continue_add'];
    $link[0]['href'] = 'course_vedio.php?act=add';

    $link[1]['text'] = $_LANG['back_list'];
    $link[1]['href'] = 'course_veido.php?act=list';

    clear_cache_files(); // 清除相关的缓存文件

    sys_msg($_LANG['articleadd_succeed'],0, $link);

}



/*------------------------------------------------------ */
//-- 编辑视频
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'edit'){

    /* 权限判断 */
    admin_priv('article_manage');
    /* 取视频数据 */
    $sql = "SELECT * FROM " .$ecs->table('course_vedio'). " WHERE vedio_id='$_REQUEST[id]'";
    $vedio = $db->GetRow($sql);
    $smarty->assign('vedio',     $vedio);
     /* 七牛上传代码 start */
   
    //ak、sk信息
    $accessKey = 'H9N6ZegIQ-cm2nIBHF9Gx4aBUK2dMUCj2zlgH4J6';
    $secretKey = 'uHzZsPd4Xds_hw1xaMixtOjOk2Ok_5iMtIZ7xJoA';
    $bucket = 'xinnuo1';
    $scope = 'xinnuo1:' .$vedio['qn_key'];
    //echo $scope;exit;
    $auth = new Auth($accessKey, $secretKey);
     
    $policy=array(
        'scope'=> $scope,
        'callbackUrl'=>'http://hu14.tophp.cn/qiniu_demo1/callback.php',
        'callbackBody' => 'key=$(key)&hash=$(etag)&description=$(x:description)&course_id=$(x:course_id)&is_show=$(x:is_show)&vedio_id=$(x:id)',
         'insertOnly'=>0

      );
     //生成上传token
     $upToken = $auth->uploadToken($bucket,$vedio['qn_key'],3600,$policy);

     $smarty->assign('uptoken',$upToken);
   /* 七牛上传代码 end */
   /* 取得课程 */
   $smarty->assign('course_list', course_list());
    $smarty->assign('ur_here',     $_LANG['article_edit']);
    $smarty->assign('action_link', array('text' => $_LANG['03_article_list'], 'href' => 'course_vedio.php?act=list&' . list_link_postfix()));
    $smarty->assign('form_action', 'update');
    $smarty->assign('img_form_action', 'update_img');
    assign_query_info();
    $smarty->display('course_vedio_info.htm');

}

/*修改本地字段*/
if ($_REQUEST['act'] =='update'){

    /* 权限判断 */
    admin_priv('article_manage');
   
    /*检查标题是否相同*/
    $is_only = $exc->is_only('title', $_POST['key'], $_POST['id'], "course_id = '{$_POST['x:course_id']}'");

    if (!$is_only)
    {
        sys_msg(sprintf($_LANG['title_exist'], stripslashes($_POST['key'])), 1);
    }
   
    $arr=array(status=>'');

    if ($exc->edit("title='{$_POST['title']}', course_id='{$_POST['course_id']}', is_show='{$_POST['is_show']}', description = '{$_POST['description']}'", $_POST['id']))

    {
        // $link[0]['text'] = $_LANG['back_list'];
        // $link[0]['href'] = 'article.php?act=list&' . list_link_postfix();

        // $note = sprintf($_LANG['articleedit_succeed'], stripslashes($_POST['title']));
        // admin_log($_POST['title'], 'edit', 'article');

        clear_cache_files();

        //sys_msg($note, 0, $link);
         $arr['status']='1';
         die(json_encode($arr));


    }
    else
    {
       $arr['status']='0';
       die(json_encode($arr));
        //die($db->error());
    }

}

/*------------------------------------------------------ */
//-- 更新视频
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'update_vedio'){

  /* 权限判断 */
    admin_priv('article_manage');

    $title=trim($_POST['title']);
    $description=$_POST['description'];
    $vedio_url = $_POST['vedio_url'];
    $add_time=gmtime();
    $course_id = $_POST['course_id'];
    $is_show = $_POST['is_show'];
    $vedio_id = $_POST['vedio_id'];
   
    //更新七牛云视频 start

     $sql = "SELECT qn_key FROM " . $ecs->table('course_vedio') . " WHERE vedio_id = '$vedio_id'";
   //你要测试的空间， 并且这个key在你空间中存在
    $bucket = 'xinnuo1';
    $old_key = $db->getOne($sql);
    $new_key = $title;
   
    $accessKey = 'H9N6ZegIQ-cm2nIBHF9Gx4aBUK2dMUCj2zlgH4J6';
    $secretKey = 'uHzZsPd4Xds_hw1xaMixtOjOk2Ok_5iMtIZ7xJoA';
  //初始化Auth状态：
  $auth = new Auth($accessKey, $secretKey);

  //初始化BucketManager
  $bucketMgr = new BucketManager($auth);
    
  //更新七牛云视频 end
   $add_time=time();
    $sql="update {$GLOBALS['ecs']->table('course_vedio')} set title='$title',description='$description',vedio_url='$vedio_url',add_time='$add_time',course_id='$course_id',is_show='$is_show',qn_key='$new_key' where vedio_id='$vedio_id'";
   
    $arr=array('status'=>'','vedio_id'=>'');
   if($GLOBALS['db']->query($sql)){
      $insert_id = $GLOBALS['db']->insert_id();
      $arr['status'] = 1;
      $arr['vedio_id'] = $vedio_id;
      echo json_encode($arr); exit;
     
   }else{
     $arr['status'] = 0;
     $arr['vedio_id'] = $vedio_id;
     echo json_encode($arr); exit;
     
   }
   

}

/*------------------------------------------------------ */
//-- 修改视频封面图片
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'update_img'){

  /* 权限判断 */
    admin_priv('article_manage');
    $vedio_id=$_POST['vedio_id'];

    $sql = "select * from {$GLOBALS['ecs']->table('course_vedio')} where vedio_id='$vedio_id'";
    $vedio_info = $GLOBALS['db']->getRow($sql);

    if($_FILES['thumb_img']['name'] && $_FILES['thumb_img']['error']==0){
       $thumb_img = $img->upload_image($_FILES['thumb_img']);
     }else{
       $thumb_img = $vedio_info['thumb_img'];
     }
   

    //echo $thumb_img;exit;
    $sql="update {$GLOBALS['ecs']->table('course_vedio')} set thumb_img='$thumb_img' where vedio_id='$vedio_id'";
    $GLOBALS['db']->query($sql);

     $link[0]['text'] = $_LANG['back_list'];
     $link[0]['href'] = 'course_vedio.php?act=list&' . list_link_postfix();

     $note = sprintf($_LANG['articleedit_succeed'], stripslashes($_POST['title']));
   
    clear_cache_files();

    sys_msg($note, 0, $link);

}




/*------------------------------------------------------ */
//-- 删除视频
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{   
    check_authz_json('article_manage');

    $vedio_id = intval($_GET['id']);

 
    /* 删除原来的视频封面图 */
     $sql = "SELECT thumb_img FROM " . $ecs->table('course_vedio') . " WHERE vedio_id = '$vedio_id'";
     $old_url = $db->getOne($sql);
     if ($old_url != '' && strpos($old_url, 'http://') === false && strpos($old_url, 'https://') === false)
     {
         @unlink(ROOT_PATH . $old_url);
     }
    
  //删除七牛云视频 start

     $sql = "SELECT qn_key FROM " . $ecs->table('course_vedio') . " WHERE vedio_id = '$vedio_id'";
   //你要测试的空间， 并且这个key在你空间中存在
    $bucket = 'xinnuo1';
    $key = $db->getOne($sql);
  
    $accessKey = 'H9N6ZegIQ-cm2nIBHF9Gx4aBUK2dMUCj2zlgH4J6';
    $secretKey = 'uHzZsPd4Xds_hw1xaMixtOjOk2Ok_5iMtIZ7xJoA';

    //初始化Auth状态：
    $auth = new Auth($accessKey, $secretKey);
   
    //初始化BucketManager
    $bucketMgr = new BucketManager($auth);
  
    //删除$bucket 中的文件 $key
   
    $qn_err = $bucketMgr->delete($bucket, $key);
   
    echo "\n====> delete $key : \n";
    if ($qn_err !== null) {
     
    } else {
        echo "Success!";
    }
  
    //删除七牛云视频 end
 
     if ($exc->drop($vedio_id))
     {
       
         clear_cache_files();
     }
     $url = 'course_vedio.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

     ecs_header("Location: $url\n");
     exit;
}



  //取出所有课程
function course_list(){

   $sql="select * from {$GLOBALS['ecs']->table('course')}";
   $course_list=$GLOBALS['db']->getAll($sql);
    //排序
    $course_list=sort_cat($course_list,0);

   foreach($course_list as $k=>$v){
     $course_list[$k]['add_time'] = local_date('Y-m-d H:i:s',$v['add_time']);
     $course_list[$k]['thumb_img']='../'.$v['thumb_img'];
   
     $course_list[$k]['description']=sub_str($v['description'],100,true);
   }

   return  $course_list;

}

/*  
   hjl：已知一个课程求其子课程
   创建像这样的查询: "IN('a','b')";
*/

  function get_course_children($all_course,$course_id){
      //print_r($all_course);exit;
     $sub_course_list=sort_cat($all_course,$course_id);

     //print_r($sub_course_list);exit;

     $course_ids=array();
     if(!empty($sub_course_list)){
         foreach($sub_course_list as $k=>$v){
           $course_ids[]=$v['course_id'];
         } 
     }
     $course_ids[]=$course_id;
      //print_r($course_ids);exit;
     return db_create_in($course_ids);

  }


//排序函数
function sort_cat($cat,$parent_id,$level=0,&$arr=array()){

   //static $arr=array();
   foreach($cat as $k=>$v){
     if($v['parent_id']==$parent_id){
        $v['level']=$level;
        $arr[]=$v;
        unset($cat[$k]);
        sort_cat($cat,$v['course_id'],$level+1,$arr);
     }
   }
  return $arr;
  //print_r($arr);exit;
}


/* 获得视频列表 */
function get_vedio_list()
{
    $result = get_filter();
    if ($result === false)
    {
        $filter = array();
        $filter['keyword']    = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['course_id'] = empty($_REQUEST['course_id']) ? 0 : intval($_REQUEST['course_id']);


        $filter['sort_by']    = empty($_REQUEST['sort_by']) ? 'cv.vedio_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = '';
        if (!empty($filter['keyword']))
        {
            $where = " AND cv.title LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
        }

    $all_course=$GLOBALS['db']->getAll("select * from {$GLOBALS['ecs']->table('course')}");


        if ($filter['course_id'])
        {
            $where .= " AND cv.course_id" . get_course_children($all_course,$filter['course_id']);
        }

        /* 视频总数 */
        $sql = 'SELECT COUNT(*) FROM ' .$GLOBALS['ecs']->table('course_vedio'). ' AS cv '.
               'LEFT JOIN ' .$GLOBALS['ecs']->table('course'). ' AS c ON c.course_id = cv.course_id '.
               'WHERE 1 ' .$where;
          //echo $sql;exit;
        $filter['record_count'] = $GLOBALS['db']->getOne($sql);
       
        $filter = page_and_size($filter);

        /* 获取视频数据 */
        $sql = 'SELECT cv.* , c.title as c_title '.
               'FROM ' .$GLOBALS['ecs']->table('course_vedio'). ' AS cv '.
               'LEFT JOIN ' .$GLOBALS['ecs']->table('course'). ' AS c ON c.course_id = cv.course_id '.
               'WHERE 1 ' .$where. ' ORDER by '.$filter['sort_by'].' '.$filter['sort_order'];

        $filter['keyword'] = stripslashes($filter['keyword']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res))
    {
        $rows['add_time'] = local_date($GLOBALS['_CFG']['time_format'], $rows['add_time']);
        $rand = mt_rand(0,10000);
        $rows['vedio_url'] = $rows['vedio_url'].'?v='.$rand;

        $arr[] = $rows;
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
} 



  